/**
  普通话等级考试-学生报名统计
*/
<template>
  <div class="student-regist-container">
    <div v-if="indexSee === 1">
      <div style="height: 30px;">
        <el-breadcrumb style="float: left;" separator="/">
          <el-breadcrumb-item :to="{ path: '/putonghuaExamsCreate' }">
          <span @click="reback()">{{ $t('mandarin.createExams') }}</span></el-breadcrumb-item>
          <el-breadcrumb-item>{{ $t('mandarin.stuRegistStatistics') }}</el-breadcrumb-item>
        </el-breadcrumb>
        <el-button style="float:right; padding:0;" type="text" @click="reback()">{{ $t('common.btn.back') }}</el-button>
      </div>
      <condition-card @reset="reset" @search="onSubmit" label-position="right" label-width="150px">
        <el-row :gutter="24" style="height: 50px;">
          <el-col :span="8">
            <el-form-item :label="$t('subjectCompetitionBase.semester')">
              <CalendarSelect :disabled='true' v-model="queryForm.condition.calendarId" @load-done="loadDone" @input='changeInput'></CalendarSelect>
              <!-- <CalendarSelect v-model="useConfigParam" @load-done="loadDone" @input='changeInput'></CalendarSelect> -->
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item :label="$t('subjectCompetitionBase.college')">
              <el-select v-model.trim="queryForm.condition.college" filterable clearable style="width: 100%">
                <el-option
                  v-for="item in options.college"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item :label="$t('subjectCompetitionBase.status')">
              <el-select v-model="queryForm.condition.status" clearable style="width: 100%">
                <el-option
                  v-for="item in options.status"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="准考证导入状态">
              <el-select v-model="queryForm.condition.importCardStatus" clearable style="width: 100%">
                <el-option
                  v-for="item in CardStatusList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </condition-card>
      <el-card shadow="never" v-loading="loading" body-style="padding: 24px;" class="card-margin">
        <h1 class="condition-title">{{$t('mandarin.studentRegist')}}</h1>
        <div class="edu-opertion-bar sub-title">
          <div class="float-left">
            <KeywordInput v-model="queryForm.condition.studentIdOrName" @enter="onSubmit" placeholder="请输入学号或姓名搜索"></KeywordInput>
            <!-- <el-input
              v-model.trim="queryForm.condition.studentIdOrName"
              :placeholder="$t('subjectCompetitionBase.studentIdOrName')"
              style="width:250px"
              @keyup.enter.native="onSubmit">
                <i slot="suffix"
                  class="el-icon-search"
                  style="margin-top:10px;cursor:pointer"
                  @click="onSubmit">
                </i>
            </el-input> -->
          </div>
          <div class="float-right" style="display: flex;">
            <el-dropdown @command="handleCommand" style="margin-right:10px">
              <el-button>
                导入准考证
                <i class="el-icon-arrow-down el-icon--right"></i>
              </el-button>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item command="import">导入准考证</el-dropdown-item>
                <el-dropdown-item command="download">{{$t('message.down')}}</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>

            <el-upload style="display: none;"
              accept=".xlsx,.xls"
              ref="upload"
              :auto-upload="true"
              action="api/competitionservice/exam/examCard/importCardInfo"
              :headers="{'X-Token': $store.state.session.sessionid}"
              :data="{competitionId: examId.id}"
              :limit="1"
              :on-success="handleSuccess"
              :on-error="handleUploadError"
              :before-upload="beforeAvatarUpload"
              :show-file-list="false"
              >
              <span slot="trigger" ref="importBtn">{{$t('universityManagement.lead')}}</span>
            </el-upload>
            <el-button type="primary" @click="batchClick">批量打印准考证</el-button>
            <el-button v-if="permitToImport" type="primary" @click="importAuditRosterClick">{{$t('mandarin.importAuditRoster')}}</el-button>
            <el-dropdown v-if="permitToExport" @command="handleExport" style="margin-right:10px">
              <el-button>
                导出学生名单
                <i class="el-icon-arrow-down el-icon--right"></i>
              </el-button>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item command="downloadSign">已报名学生名单</el-dropdown-item>
                <el-dropdown-item command="downloadNoSign">未报名学生名单</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>

            <el-upload style="display: none;"
              class="upload-demo"
              :auto-upload="true"
              action="api/competitionservice/signUp/student/import"
              :headers="{'X-Token': $store.state.session.sessionid}"
              :data="{bucketname: 'face', folderpath: 'file',competitionId:examId.id}"
              :limit="1"
              :on-success="handleSuccess"
              :before-upload="beforeAvatarUpload"
              :file-list="fileList"
              :show-file-list="false"
              >
              <span slot="trigger" ref="selectFile">{{$t('internship.selectFile')}}</span>
            </el-upload>
          </div>
        </div>
        <edu-table :pagination="false" :tooltipEffect="tooltipEffect" stripe :data="dataList" size="mini" @selection-change="handleSelectionChange">
          <edu-table-column :label="$t('subjectCompetitionBase.studentId')" prop="studentId"></edu-table-column>
          <edu-table-column :label="$t('subjectCompetitionBase.name')" prop="studentName"></edu-table-column>
          <edu-table-column :label="$t('subjectCompetitionBase.sex')" prop="sex"></edu-table-column>
          <edu-table-column :label="$t('subjectCompetitionBase.college')" prop="collegeName"></edu-table-column>
          <edu-table-column :label="$t('subjectCompetitionBase.status')" prop="statusName"></edu-table-column>
          <edu-table-column :label="$t('collegeRegistStatistics.testTime')" prop="examTime"></edu-table-column>
          <edu-table-column label="准考证导入状态" prop="cardId" min-width="120">
            <template slot-scope="scope">
              {{ scope.row.cardId?'导入':'未导入'}}
            </template>
          </edu-table-column>
          <edu-table-column :label="$t('common.text.operation')" fit  >
              <template slot-scope="scope">
                <el-button v-if="scope.row.status==2&&scope.row.cardId"  type="text" @click="SeeClick(scope.row,1)">查看准考证</el-button>
              </template>
            </edu-table-column>
        </edu-table>
        <el-row type="flex" class="row-bg" justify="end">
          <el-col>
            <el-pagination
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="queryForm.pageNum_"
              :page-sizes="[20, 40, 80, 100]"
              :page-size="queryForm.pageSize_"
              layout="total, sizes, prev, pager, next, jumper"
              :total="queryForm.total_"
              style="float:right;margin-top:10px"
            ></el-pagination>
          </el-col>
        </el-row>
      </el-card>
      <edu-export-dialog
        :disabled="exportButton"
        :title="$t('message.prompt')"
        ref="downloadRef"
        :data="exportResult">
      </edu-export-dialog>
    </div>
     <!-- 查看准考证 -->
    <div v-if="indexSee === 2" ref="msg" id="msg">
      <viewAdmissionCard :signUpId="signUpId" @change-exam-create-index="changeExamCreateIndex()"></viewAdmissionCard>
    </div>
  </div>
</template>
<script>
import subjectCompetitionApi from 'common/src/api/subjectCompetition/subjectCompetition';
import graduateStudent from 'common/src/api/graduateStudent/graduateStudent';
import viewAdmissionCard from './viewAdmissionCard';
// import { queryMutualDicListName } from "common/src/api/dictionary";
// import { queryMutualDic } from "common/src/api/dictionary";
import { queryDic } from "common/src/api/dictionary";
import UTILS from "common/src/utils/utils";
import tools from 'common/src/views/underGraduationDesign/tools.js';
export default {
  props: {
    examId: {
      type: Object,
      default() {
        return {};
      }
    }
  },
  components: {
    viewAdmissionCard
  },
  data () {
    return {
      indexSee:1,
      auths: [],
      fileList: [],
      cardIds:[],
      permitToImport: true,
      permitToExport: true,
      importAuditRoster: false,
      multipleSelection: [],
      CardStatusList:[
        {
          value: 0,
          label: '未导入'
        },
        {
          value: 1,
          label: '导入'
        }
      ],
      queryForm: {
        pageNum_: 1,
        pageSize_: 20,
        total_: 0,
        condition: {
          "importCardStatus":'',
          "competitionId": this.examId.id,
          "calendarId": "",
          // "calendarName": "",
          "college": "",
          "status": "",
          "studentIdOrName": ""
        }
      },
      loadList: [],
      semesterRmpor: [],
      options: {
        college: [],
        status: [
          {
            label: '已报名',
            value: 1
          },
          {
            label: '待报名',
            value: 0
          },
          {
            label: '报名成功',
            value: 2
          },
          {
            label: '无资格',
            value: 3
          }
        ]
      },
      calendarName: '',
      useConfigParamList: '',
      useConfigParam: '',
      dataList: [],
      exportButton: false,
      exportResult: null
    }
  },
  filters: {
    status(val) {
      switch (val) {
        case 0:
          return '已报名'
        case 1:
          return '报名结束'
        default:
          return val
      }
    }
  },
  created() {
    // 获取当前用户auths权限
    if (localStorage.getItem("sessiondata")) {
      if (JSON.parse(localStorage.getItem("sessiondata")).auths) {
        this.auths = JSON.parse(localStorage.getItem("sessiondata")).auths;
      }
    }
    this.getSchoolCalendar()
    // this.getListData()
    this.getOptions()
    // subjectCompetitionApi.englishListsetStatisticsCollege(Number(this.$store.getters.getProjectId())).then(res => {
    //   // console.log(res, 'College');
    //   if (res.data) {
    //     res.data.forEach(el => {
    //       if (el) {
    //         this.options.college.push({
    //           value: el,
    //           label: el
    //         })
    //       }
    //     });
    //   }
    // })
  },
  methods: {
    getSchoolCalendar() {
      graduateStudent.schoolCalendar().then(res => {
        this.semesterRmpor = res.data;
        this.semesterRmpor.forEach(el => {
          if (el.fullName=== this.examId.calendarYearTerm) {
            this.queryForm.condition.calendarId = el.id;
          }
        });
      }).then(() => {
        this.getListData()
      });
    },
    // 上传成功
    handleSuccess(res, file, fileList) {
      if (!file.name.endsWith(".xlsx") && !file.name.endsWith(".xls")){
        this.fileList = [];
        this.clearFiles();
        return this.$message.warning(this.$t('cetStatistics.formatError'))

      }
      if(res.code!=200) {
        this.fileList = [];
        this.$message(res.msg);
      } else {
        this.$message.success(this.$t('studentsRegist.successfully'));
        this.queryForm.pageNum_ = 1;
        this.fileList = [];
      }
      this.getListData();
      this.clearFiles();
    },
    clearFiles() {
			this.$refs.upload.clearFiles();
		},
    beforeAvatarUpload(file) {
			let extName = file.name
				.substring(file.name.indexOf(".") + 1)
				.toLowerCase()
				.trim();
			if (!(extName === "xls" || extName === "xlsx")) {
				this.$message({
					type: "error",
					message: this.$t('cetStatistics.formatError')
				});
        this.fileList = [];
				this.clearFiles();
				return;
			}
			if (!(file.size / 1024 / 1024 < 10)) {
				this.$message({
					type: "error",
					message: '文件大小不能超过10M'
				});
        this.fileList = [];
				this.clearFiles();
				return;
			}
		},
    cancelClose() {},
    // 校验特殊字符$
    checkSpecial(rule, value, callback) {
      let regEn = /[`$]/im;
      if (regEn.test(value)) {
        callback(new Error(this.$t('graduateBase.specialText')))
      } else {
        callback();
      }
    },
    reback() {
      this.$emit('change-exam-create-index')
    },
    getListData() {
      subjectCompetitionApi.poststudentRegistraList(this.queryForm).then((res) => {
        this.dataList = res.data.list;
        this.queryForm.total_ = res.data.total_;
      })
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
      this.cardIds=[];
      this.multipleSelection.forEach((item,index)=>{
        if(item.cardId){
          this.cardIds.push(item.cardId);
        }
      })
      this.cardIds=[...new Set(this.cardIds)];
    },
    loadDone(data, val) {
      this.loadList = data;
      this.loadList.forEach(el => {
        if (el.id === val) {
          // this.queryForm.condition.calendarName = el.fullName;
          // this.calendarName = el.fullName;
          this.useConfigParamList = val;
        }
      });
      // this.postInternshipSet(this.queryForm);
    },
    changeInput(val) {
      // this.loadList.forEach(el => {
      //   if (el.id === val) {
      //     this.queryForm.condition.calendarName = el.fullName;
      //   }
      // });
    },
    onSubmit() {
      this.queryForm.pageNum_ = 1;
      this.getListData();
    },
    // 导入审核名单
    importAuditRosterClick() {
      // console.log('dfd',this.$refs.selectFile);
      this.$refs.selectFile.click();

      // this.importAuditRoster = true;
    },
    // 轮询直到获取key值的接口返回
    cycleToGetKey() {
      setTimeout(() => {
        let currentIds = [];
        if (this.multipleSelection.length > 0) {
          this.multipleSelection.forEach((element) => {
            currentIds.push(element.id);
          });
        }
        subjectCompetitionApi.poststudentExport({
          "competitionId": this.examId.id,
          "calendarId": this.queryForm.condition.calendarId,
          "college": this.queryForm.condition.college,
          "studentIdOrName": this.queryForm.condition.studentIdOrName,
          "status": this.queryForm.condition.status,
          "selectRowIds": currentIds
        }).then(res => {
          if (res.success) {
            this.$refs.downloadRef.close();
            this.exportButton = false;
            this.normalDelayRequest(res.key, res.msg);
          } else {
            this.cycleToGetKey();
          }
        });
      }, 3000);
    },
    cycleToGetKeyNoSign() {
      setTimeout(() => {
        let currentIds = [];
        if (this.multipleSelection.length > 0) {
          this.multipleSelection.forEach((element) => {
            currentIds.push(element.id);
          });
        }
        console.log(123)
        subjectCompetitionApi.poststudentNoSignExport({
          "competitionId": this.examId.id,
          "calendarId": this.queryForm.condition.calendarId,
          "college": this.queryForm.condition.college,
          "studentIdOrName": this.queryForm.condition.studentIdOrName,
          "status": this.queryForm.condition.status,
          "selectRowIds": currentIds
        }).then(res => {
          if (res.success) {
            this.$refs.downloadRef.close();
            this.exportButton = false;
            this.normalDelayRequest(res.key, res.msg);
          } else {
            this.cycleToGetKeyNoSign();
          }
        });
      }, 3000);
    },
    // 导出异步
    delayRequest(key, name) {
      setTimeout(() => {
        subjectCompetitionApi.downloadGetKey(key, name).then(res => {
          this.exportResult = res.data;
          if (res.code == 200 && res.data.status) {
            this.exportButton = false;
            let path =
              '/api/competitionservice/competitionExport/file?path=' +
              res.data.path + '&name=' + name;
            // window.open(path);
            window.location.href = path;
            this.$message.success(this.$t('result.exportSuccessfully'));
            this.$refs.downloadRef.close();
          } else {
            this.delayRequest(key, name);
          }
        });
      }, 3000);
    },
    // Normal导出异步
    normalDelayRequest(key, name) {
      setTimeout(() => {
        subjectCompetitionApi.downloadGetKey(key).then(res => {
          this.exportResult = res.data;
          if (res.code == 200 && res.data.status) {
            this.exportButton = false;
            let path =
              '/api/competitionservice/competitionExport/file?path=' +
              res.data.path + '&name=' + name;
            // window.open(path);
            window.location.href = path;
            this.$message.success(this.$t('result.exportSuccessfully'));
            this.$refs.downloadRef.close();
          } else {
            this.delayRequest(key, name);
          }
        });
      }, 3000);
    },
    // 导出
    exportAuditRoster(data) {
      // 1、第一步：调该接口，获取key值以及msg中的文件名
      // 2、第二步：将key值放入接口传参
      // 3、第三步：传入path值以及name(msg中的文件名)值，下载文件
      this.exportResult = null;
      this.$refs.downloadRef.open();
      this.exportButton = true;
      if(data == 1){
        this.cycleToGetKey();
      }else{
        this.cycleToGetKeyNoSign();
      }
    },
    handleSizeChange(val) {
      this.queryForm.pageSize_ = val;
      this.queryForm.pageNum_ = 1;
      this.getListData();
    },
    handleCurrentChange(val) {
      this.queryForm.pageNum_ = val;
      this.getListData();
    },
    getOptions() {
      // 筛选条件字典查询
      let data = {
        lang: this.$store.getters.language || "cn",
        type: "allChild",
        keys: ["X_PYCC", 'X_PYLB', 'X_XWLX', 'X_XXXS', 'X_YX']
      };
      queryDic(data).then(res => {
        UTILS.fillSelect(
          {
            trainingCategory: "X_PYLB",
            degreeType: "X_XWLX",
            formLearning: "X_XXXS",
            college: "X_YX",
            TrainingLevel: "X_PYCC"
          },
          res.data,
          this.options
        );
      });
    },
    reset() {
      // this.baseLevel = [];
      // Object.keys(this.queryForm.condition).forEach(key => this.queryForm.condition[key] = '');
      this.queryForm.condition.college = '';
      this.queryForm.condition.status = '';
      this.queryForm.condition.studentIdOrName = '';
      this.queryForm.condition.importCardStatus = '';
      // console.log(this.useConfigParamList, this.useConfigParam);

      // this.queryForm.condition.calendarId = this.useConfigParamList;
      // this.useConfigParam = this.useConfigParamList;
      // this.queryForm.condition.calendarName = this.calendarName;
      // this.onSubmit();
      this.queryForm.pageNum_ = 1;
      this.getListData();
    },
    //查看准考证
    SeeClick(rows,tip){
      this.signUpId=rows;
      this.indexSee=2;
    },
    // 返回列表页
    changeExamCreateIndex() {
      this.indexSee = 1
    },
    // 处理导入
    handleCommand(command) {
      if (command && command === "import") {
        // 模板导入
        this.$refs.importBtn.click();
      } else if (command && command === "download") {
        // 模板下载
        this.downloadTemplate();
      }
    },
    // 模板下载
    downloadTemplate(){
      subjectCompetitionApi.downloadStudents();
    },
    handleUploadError(err) {
      this.$message({
        type: 'error',
        message: err
      })
    },
    // 处理导出
    handleExport(command) {
      if (command && command === "downloadSign") {
        // 已报名
        this.exportAuditRoster(1)
      } else if (command && command === "downloadNoSign") {
        // 未报名
        this.exportAuditRoster(0);
      }
    },
    // 准考证批量打印
    batchClick() {
      let data={
        competitionId: this.examId.id,
        cardIds:this.cardIds?this.cardIds:''
      }
      subjectCompetitionApi.exportBatch(data)
    },

  },
  watch: {
    auths: {
      handler(newVal) {
        if (newVal && Array.isArray(newVal) && newVal.length > 0) {
          newVal.some(item => {
            if (item.authCode === 'graduateStu-tempSet-export') {
              this.permitToExport = true;
            }
            if (item.authCode === 'graduateStu-tempSet-add') {
              this.permitToAdd = true;
            }
          });
        }
      },
      deep: true,
      immediate: true
    }
  }
}
</script>
<style lang="scss" scoped>
  .student-regist-container ::v-deep {
    .el-breadcrumb__item:last-child ::v-deep {
      .el-breadcrumb__inner {
        color: #606266;
        font-weight: bold;
        cursor: default
      }
    }
    .el-breadcrumb__item ::v-deep {
      .is-link {
        color: #aaa;
        font-weight: unset;
      }
      .is-link:hover {
        color: #409eff;
      }
    }
  }
</style>
